package com.zhk.entry.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class ThreadConn{

    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();

    // Map中存放的是会用到的数据源
    private static Map<String,ThreadLocal<Connection>> dataSourceMap =new HashMap<>();

    private static final String DRIVER = "com.mysql.jdbc.Driver";

    //用来拼接的数据库名称
    private static String dataName = null;

    public  void setDataName(String dataName)
    {
        this.dataName = dataName;
    }
//    private   String URL = "jdbc:mysql://localhost:3306/"+dataName+"?\"\n" +
//            "\t\t\t+ \"useUnicode=true&characterEncoding=UTF-8";
//
//
//    private static final String UNAME = "root";
//    private static final String PWD = "root";


    public  Connection getConnection() {


        Connection conn = null;

        String URL = "jdbc:mysql://localhost:3306/"+dataName+"?\"\n" +
                "\t\t\t+ \"useUnicode=true&characterEncoding=UTF-8";

        String DRIVER = "com.mysql.jdbc.Driver";
        final String UNAME = "root";
        final String PWD = "root";

        //查看该数据库的连接是否已存在
        ThreadLocal<Connection> connectionThreadLocal = dataSourceMap.get(dataName);
        if(connectionThreadLocal != null)
        {
            conn = connectionThreadLocal.get();
        }

        //如果在当前线程中没有绑定相应的Connection
        if (conn == null) {
            try {
                Class.forName(DRIVER);
                //2、获取数据库连接
                conn = DriverManager.getConnection(URL, UNAME, PWD);
                //将Connection设置到线程变量ThreadLocal中
                connectionHolder.set(conn);
                dataSourceMap.put(dataName,connectionHolder);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    /**
     * 关闭自动事务
     * @throws SQLException
     */
    public  void startTransaction() throws SQLException {
        getConnection().setAutoCommit(false);
    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public  void commitTransaction() throws SQLException {
        getConnection().commit();
    }

    /**
     * 事务的回滚
     * @throws SQLException
     */
    public  void rollbackTransaction() throws SQLException {
        getConnection().rollback();
    }

}
